<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/13
 * Time: 14:27
 */

namespace app\index\controller;

use app\common\controller\PayBase;
use think\Db;
use app\index\model\ChongzhiList;
use think\Exception;

class Paycrzf extends PayBase{
    protected $partner;
    protected $key;
    protected $pay_url;
    protected $back_url;
    protected $success_url;
    protected $fail_url;

    public function __construct() {
        parent::__construct();
//        $this->partner = '32eb743acaaf46d8b727f233a027b25d';
        $this->partner = '154399';
        $this->key = 'f5fb23ba69f0455d860cb9db583b94e6';
        $this->pay_url = 'http://wl.xitangsoft.com/chao/payjson';
        $this->back_url = 'http://www.my67.cc/index/Paycrzf/callBack';
        $this->success_url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index/Paycrzf/successUrl';
        $this->fail_url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index/Paycrzf/failUrl';
    }

    public function initPay($username='',$pay_type='',$amount=-1,$from=0){
        //接收数据
        $user = cookie('username','');
        $password = cookie('password','');
        $username =  empty($username) ? input('post.username','') : $username;
        $pay_type = empty($pay_type) ? input('post.pay_type','') : $pay_type;
        $amount = -1==$amount ? input('post.amount',0) : $amount;
        $ctime = time();

        if($pay_type=='null' || $pay_type=='') return packJson('',$pay_type.'请选择支付方式',500);
        $pay_method = Db::name('pay_type_list')
            ->alias("a")
            ->join('__PAY_METHOD__ b','a.method_id=b.id','LEFT')
            ->where(['a.method'=>15,'a.type_value'=>$pay_type])
            ->field('a.type_name,b.name,b.id,b.method,b.money')->find();

        $remark = $pay_method['type_name'].'-'.$pay_method['name'];

        //验证用户信息
        if( 0==$from ){
            if(!$user || !$username || ($user!=$username)) return packJson('','用户身份验证失败',500);
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username,'password'=>$password])->find();
        }else{
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username])->find();
        }
        if(!$user_info) return packJson('','用户身份验证失败',500);
        if($user_info['swzh'] == 1) return packJson('','试玩账号无法充值',500);
        if($user_info['nbzh'] == 1) return packJson('','内部账号不支持线上充值',500);

        //充值防骚扰是否开启，并进行处理
        $harassment = Db::name('xt_czfsr')->find();
        if($harassment['open'] > 0) {
            $nowys = $ctime - $harassment['time_xs'] * 60;
            $old_czjl = Db::name('chongzhi_list')->where('username',$username)->where('cztime','>',$nowys)->find();
            if($old_czjl['id'] > 0) {
                return packJson('',"系统充值防骚扰已开启，{$harassment['time_xs']}分钟内只能充值1次！",500);
            }
        }
        //生成订单号
        $order_sn = 'CRF' . str_pad($user_info['id'],5,'0',STR_PAD_LEFT) . $ctime . rand(111,999);
        //组装数据
        if( 1==$from ){
            $this->success_url.="Third";
            $this->fail_url.="Third";
        }
        $data = array();
        $data['merchantid'] = $this->partner;            #商户号
        $data['type'] = $pay_type;
        $data['m'] = $amount;
        $data['orderid'] = $order_sn;                    #订单号
        $data['callbackurl'] = $this->back_url;
        $data['sign'] = md5($this->partner.'&'.$pay_type.'&'.$amount.'&'.$order_sn.'&'.$this->back_url.'&'.$this->key);
        $data['gotrue'] = $this->success_url;
        $data['gofalse'] = $this->fail_url;
        $data['uid'] = $username;

        $res =  self::curl_post_https($this->pay_url,$data);
        $res = json_decode($res,true);
        $status = isset($res['status']) ? $res['status'] : 0;

        if( 1==intval($status) ){
            $u = Db::name('username')->where('username',$username)->value('je');
            $model = new ChongzhiList();
            if($model->setTransRechargeInfo($order_sn,$amount,$username,0,0,1,$remark,$ctime,'超人线上支付','系统自动',get_ip(),0,$pay_type,0,0,0,0,$user_info['us_class'],'',0,0,$u)){
                //跳转支付页
                if( '104'==$pay_type || '103'==$pay_type ){
//                    return packJson($res['qRTxt'],'',203);
                    /*$url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/api/Pay/payDetail?img='.base64_encode($res['qRImg']).'&money='.$amount.'&url='.base64_encode($res['qRTxt']);*/
                    $res['h5'] = base64_encode(openssl_encrypt($res['h5'], 'aes-128-cbc', 'uwu6263787ewmyyc', true, '1234567890123456'));
                    return packJson(['img'=>$res['qRImg'],'url'=>$res['qRTxt'],'name'=>$res['aliName'],'sn'=>$order_sn,'android_url'=>$res['h5']],'',202);
                }
                return packJson($res['qRTxt'],'',200);
            }else{
                return packJson('',"订单生产错误",500);
            }
        }else{
            return packJson('',$res['msg'],500);
        }
    }
    public function callBack(){
        file_put_contents('crzf_back.txt',var_export(input(),true),FILE_APPEND);
        $sign = input('sign','');
        $ordernumber = input('oid','');
        $orderstatus = input('status',0);
        $paymoney = input('m',0);
        $sysnumber = input('oidPay','');
        $attach = input('uid','');

        $sign_str = $ordernumber.'&'.$orderstatus.'&'.$paymoney.'&'.$this->key;
        if (md5($sign_str) == $sign && 1==intval($orderstatus)) {

            $order_info = Db::name('chongzhi_list')->where('ddbh',$ordernumber)->find();
            $user_info = Db::name('username')->where('username',$order_info['username'])->find();
            if( 1==intval($order_info['zt']) ){
                header('HTTP/1.1 200 OK');exit;
            }
            Db::startTrans();
            try {
                //计算优惠金额
                $msje = $msbs = 0;
                $cz_set = Db::name('xt_chongzhi')->find();
                $user_class = Db::name('us_class')->where('id',$user_info['us_class'])->find();
                $zsje = $paymoney * $user_class['czzsbl'] / 100;
                $zsbs = $user_class['czzsbl'];
                if($paymoney >= $cz_set['xscz_je']) {
                    $msje = $paymoney * $cz_set['xscz_zs'] / 100;
                    $msbs = $cz_set['xscz_zs'];
                }
                //充值方案赠送
                $pay_method = Db::name('pay_type_list')
                    ->alias("a")
                    ->join('__PAY_METHOD__ b','a.method_id=b.id','LEFT')
                    ->where(['a.method'=>13,'a.type_value'=>trim($order_info['liuyan'])])
                    ->field('a.type_name,b.name,b.id,b.method,b.money')->find();
                $method_money = 0.00;
                if( floatval( $pay_method['money'] ) > 0 ){
                    if( 0==intval( $pay_method['method'] ) ){
                        //金额
                        $method_money = $pay_method['money'];
                    }else{
                        //比例
                        $method_money = floatval($paymoney) * floatval($pay_method['money']) / 100;
                    }
                }
                $method_money = sprintf("%.2f",substr(sprintf("%.3f", $method_money), 0, -2));
                if( (sprintf("%.2f",$paymoney)!=sprintf("%.2f",$order_info['je'] )
                        || sprintf("%.2f",$zsje)!=sprintf("%.2f",$order_info['hy_zsje'])
                        || sprintf("%.2f",$zsbs)!=sprintf("%.2f",$order_info['hy_zsbs'])
                        || sprintf("%.2f",$msje)!=sprintf("%.2f",$order_info['hy_msje'])
                        || sprintf("%.2f",$msbs)!=sprintf("%.2f",$order_info['hy_msbs'])
                        || sprintf("%.2f",$method_money)!=sprintf("%.2f",$order_info['method_money']) )
                    && !Db::name('chongzhi_list')->where(['id'=>$order_info['id']])->update(['je'=>$paymoney,'hy_zsje'=>$zsje,'hy_zsbs'=>$zsbs,'hy_msje'=>$msje,'hy_msbs'=>$msbs,'method_money'=>$method_money]) ){
                    throw new Exception("更新订单信息金额错误");
                }

                $dml_set = Db::name('xt_dmsz')->where('id',1)->find();
                if( 1==$cz_set['dmopen'] ){
                    $dmls = (floatval($msje) + floatval($zsje) + floatval($paymoney)+ floatval($method_money)) * $dml_set['xscz_dmbs'];
                }else{
                    $dmls = floatval($paymoney) * $dml_set['xscz_dmbs'];
                }
                //充值后账户总金额
                $czhje = floatval($msje) + floatval($zsje) + floatval($paymoney)+ floatval($method_money) + floatval($user_info['je']);
                //充值总金额
                $czzje = floatval($paymoney) + floatval($user_info['czzje']);
                //用户当前打码量
                $dml = $user_info['dml'] + $dmls;

                if( !model('ChongzhiList')->updateRechargeInfo($ordernumber,$sysnumber,1,$czhje,time()) ){
                    throw new Exception("更新订单信息错误");
                }
                if( !model('Username')->upUserXsczInfo($czhje,$dml,$czzje,$order_info['username']) ){
                    throw new Exception("更新用户金额错误");
                }
                Db::name('username')->where('username',$order_info['username'])->setInc('cz_num');

                $fav_money = floatval($msje)+floatval($zsje)+ floatval($method_money);
                //满送金额，等级赠送金额，充值方案赠送金额
                $extcj = array(
                    'username'=>$user_info['username'],
                    'user_class'=>$user_info['us_class'],
                    'fstime'=>time(),
                    'czadmin' => '系统赠送',
                );
                $cjhje = floatval($paymoney) + floatval($user_info['je']) + floatval($msje);

                if( floatval($msje) > 0 ){
                    $extcj['beizhu'] = '系统赠送，充值满送金额';
                    $extcj['cjje'] = $msje;
                    $extcj['cjhje'] = $cjhje;
                    Db::name('caijin_list')->insert($extcj);
                }
                $cjhje += floatval($zsje);
                if( floatval($zsje) > 0 ){
                    $extcj['beizhu'] = '系统赠送，充值等级赠送金额';
                    $extcj['cjje'] = $zsje;
                    $extcj['cjhje'] = $cjhje;
                    Db::name('caijin_list')->insert($extcj);
                }
                $cjhje += floatval($method_money);
                if( floatval($method_money) > 0 ){
                    $extcj['beizhu'] = '系统赠送，充值方案赠送金额';
                    $extcj['cjje'] = $method_money;
                    $extcj['cjhje'] = $cjhje;
                    Db::name('caijin_list')->insert($extcj);
                }

                $data = array('username' =>$order_info['username'],'test'=>"您账户充值金额：{$paymoney}，赠送金额：{$fav_money}。已充值到账，请注意查收！",'xx_time'=>time(),'ifdq'=>0);
                Db::name('xiaoxi')->data($data)->insert();
                Db::commit();
                header('HTTP/1.1 200 OK');exit;
            } catch (\Exception $e) {
                Db::rollback();
                header('HTTP/1.1 400 Bad Request');
                exit;
            }
        }
        header('HTTP/1.1 400 Bad Request');
    }
    public function successUrl(){
        $this->buildHtml("充值成功!");
    }
    public function successUrlThird(){
        $this->buildHtml("充值成功",1);
    }
    public function failUrl(){
        $this->buildHtml("充值失败!");
    }
    public function failUrlThird(){
        $this->buildHtml("充值失败",1);
    }
    private function curl_post_https($url,$data){ // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }
}